<template>
  <div class="app-container">
    <el-card>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="新闻封面" prop="cover" class="cover">
          <oss v-model="form.cover" :limit="1" ossURL="/oss/uploadPicNews" />
        </el-form-item>
        <el-form-item label="新闻标题" prop="newsTitle">
          <el-input  maxlength="50" v-model="form.newsTitle" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="新闻说明" prop="newsDiscription">
          <el-input type="textarea" maxlength="100" show-word-limit v-model="form.newsDiscription" placeholder="请输入新闻说明" />
        </el-form-item>
        <el-form-item label="新闻内容" prop="content">
          <editor v-model="form.content" height="500px" />
        </el-form-item>
        <el-form-item label="启用状态" prop="enabled">
          <el-switch v-model="form.enabled" :active-value="1" :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addNews, updateNews } from "@/api/news/news";
import rule from "@/rules/news.js";

export default {
  name: "newsAdd",
  components: {
    oss: () => import("@/components/ImageUpload/oss.vue"),
  },
  data() {
    return {
      form: {
        id: undefined,
        cover: undefined,
        newsTitle: undefined,
        newsDiscription: undefined,
        content: undefined,
        enabled: undefined,
      },
      rules: rule,
    };
  },

  created() {
    let news = sessionStorage.getItem("news");

    if (!news) {
      return;
    }
    this.form = JSON.parse(news);
  },

  methods: {
    // 取消按钮
    cancel() {
      this.reset();
      this.$router.push({
        path: "/news",
      });
    },


    // 表单重置
    reset() {
      this.form = {
        id: null,
        cover: null,
        newsTitle: null,
        newsDiscription: null,
        content: null,
        enabled: null,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }

        if (!this.form.id) {
          return;
        }

        updateNews(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.cancel();
        });
      });
    },
  },
};
</script>

<style scoped>
.cover>>>.el-upload-dragger {
  width: 150px;
  height: 150px;
}
</style>

